package com.wc.service.impl;

import com.wc.dao.AuthorizeMapper;
import com.wc.pojo.Authorize;
import com.wc.service.AuthorizeService;
import com.wc.util.Page;
import com.wc.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 授权实现类
 */
@Service
public class AuthorizeServiceImpl implements AuthorizeService {

    @Autowired
    private AuthorizeMapper mapper;

    protected static Logger logger = LoggerFactory.getLogger(AuthorizeServiceImpl.class);

    @Override
    public List<Authorize> getAuthorizelistall(int pageNo, int pageSize) {
        Page.checkPage(pageNo,pageSize);
        return mapper.getAuthorizelist(pageNo,pageSize);
    }

    @Override
    public Authorize getAuthorize() {
        return mapper.getAuthorize();
    }

    @Override
    public Page<Authorize> getAuthorizelist(int pageNo, int pageSize) {
        Page.checkPage(pageNo,pageSize);
        Page<Authorize> page = new Page<>();
        try {
            page.setPageNo(pageNo);
            page.setPageSize(pageSize);
            int tatalCount = mapper.getAuthorizecount();
            page.setTotalCount(tatalCount);
            int totalPage = tatalCount % pageSize == 0 ? tatalCount / pageSize : tatalCount / pageSize + 1;
            page.setTotalPage(totalPage);
            List<Authorize> list = mapper.getAuthorizelist((pageNo - 1) * pageSize,pageSize);
            page.setList(list);
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
        return page;
    }

    @Override
    @Transactional
    public boolean pastAuthorize(Authorize authorize) {
        boolean result = false;
        try {
            if (StringUtils.isEmpty(authorize.getSqBmdm()) || StringUtils.isEmpty(authorize.getSqXmdm()) || StringUtils.isEmpty(authorize.getSqOwnerid())){
                throw new Exception("授权的基本信息不能为空");
            }
            Authorize oldAuthorize = mapper.getOwnerid(authorize.getSqOwnerid());
            if (!StringUtils.isEmpty(oldAuthorize)){
                throw new Exception("该项目已经授权");
            }
            if (StringUtils.isEmpty(authorize.getSqTime())){
                authorize.setSqTime(new Date());
            }
            //查询将要授权过去的信息
            int row = mapper.addAuthorize(authorize);
            if (row > 0) {
                logger.info("授权成功");
                result = true;
            } else {
                logger.error("授权失败");
                result = false;
            }
        }catch (Exception e){
            logger.debug(e.getMessage());
        }
        return result;
}


}
